package com.honry.identityaccess.application;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import com.honry.identityaccess.application.command.UserCommand;
import com.honry.identityaccess.domain.model.DomainRegistry;
import com.honry.identityaccess.domain.model.identity.ContactInfo;
import com.honry.identityaccess.domain.model.identity.EmailAddress;
import com.honry.identityaccess.domain.model.identity.Person;
import com.honry.identityaccess.domain.model.identity.Telephone;
import com.honry.identityaccess.domain.model.identity.User;
import com.honry.identityaccess.domain.model.identity.UserRepository;
import com.honry.identityaccess.application.command.ChangeUserPasswordCommand;
@Transactional
public class IdentityApplicationService {
	@Autowired
    private UserRepository userRepository;
	@Transactional
	public User addUser(UserCommand userCommand){
		User user =new User(
				userCommand.getUserName(), 
				userCommand.getPassword(),
				new Person(userCommand.getName(),
				new ContactInfo(new EmailAddress(userCommand.getEmailAddress()), 
				new Telephone(userCommand.getPrimaryTelephone()))));
		
		
		this.userRepository().add(user);
		return user;
	}
	@Transactional
    public void changeUserPassword(ChangeUserPasswordCommand aCommand) {
        User user = this.existingUser(aCommand.getUsername());

        user.changePassword(aCommand.getCurrentPassword(), aCommand.getChangedPassword());
    }
	private User existingUser( String aUsername) {
        User user = this.user( aUsername);

        if (user == null) {
            throw new IllegalArgumentException(
                    "User does not exist for: "
                     + aUsername);
        }

        return user;
    }
	@Transactional(readOnly=true)
    public User user(String aUsername) {
        User user =
                this.userRepository()
                    .userWithUsername(
                            aUsername);

        return user;
    }
	private UserRepository userRepository(){
		return this.userRepository;
	}
}
